package com.cn.kehong.exception;

import com.cn.kehong.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.javassist.tools.web.BadHttpRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;

import javax.servlet.http.HttpServletRequest;
import java.net.ConnectException;
import java.net.SocketException;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

import static com.cn.kehong.exception.GlobalExceptionUtil.covert;

/**
 * Created with IntelliJ IDEA. User: admin Date: 2023/9/6 Time: 15:09 To change this template use
 * File | Settings | File Templates. Description:
 */
@Aspect
@Component
public class WebExceptionHandle {

  Logger logger = LoggerFactory.getLogger(WebExceptionHandle.class);

  private final static String TOKEN_PREFIX = "front_token:";

  @Autowired
  HttpServletRequest httpServletRequest;

  @Autowired
  RedisTemplate redisTemplate;

  @SuppressWarnings("rawtypes")
  @Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
  public Object execute(ProceedingJoinPoint pjp) throws Throwable {
    try {
      String requestUri = httpServletRequest.getRequestURI();
      String contextPath = httpServletRequest.getContextPath();
      String url = requestUri.substring(contextPath.length());
      System.out.println("WebExceptionHandle:"+url);
      if(!Constants.WHITELIST.contains(url) && url.indexOf(Constants.API_URL) < 0 && url.indexOf(Constants.FIRST_URL) < 0 && url.indexOf(Constants.DOWNLOAD_URL) < 0&&url.indexOf(Constants.DIST) < 0){
        //获取参数
        Object[] args = pjp.getArgs();
        String token = "";
        for(int i = args.length -1;i >=0;i--){
          if(args[i] instanceof String && args[i].toString().indexOf(TOKEN_PREFIX) ==0){
            token = args[i].toString().replace(TOKEN_PREFIX,"");
          }
        }
//        if(StringUtils.isEmpty(token)){
//          logger.error("未获取到token");
//          return covert("未获取到token",-10000);
//        }
//        String sessionId = httpServletRequest.getSession().getId();
//        String existToken = (String) redisTemplate.opsForValue().get(sessionId);
//        if(!StringUtils.equals(existToken,token)){
//          logger.error("【服务器token】"+existToken+"【前台传递token】"+token);
//          return covert("token已失效，请刷新页面或者重新登录",-10000);
//        }
//        redisTemplate.opsForValue().set(sessionId,existToken, 10, TimeUnit.MINUTES);

      }

      Object target = pjp.getTarget().getClass().getName();
      logger.info("调用类名："+target);
      return pjp.proceed();
      // 网络连接错误
    } catch (ConnectException e) {
      logger.error("connect exception: ", e);
      return covert(GlobalExceptionUtil.COMMON_REQUEST_FAIL, e);
      // 网络错误
    } catch (SocketException e) {
      logger.error("socket exception: ", e);
      return covert(GlobalExceptionUtil.COMMON_NETWORK_EXCEPTION, e);
      // bad request
    } catch (BadHttpRequest e) {
      logger.error("socket exception: ", e);
      return covert(GlobalExceptionUtil.COMMON_PARAMS_EXCEPTION, e);
      // sql报错
    } catch (SQLException e) {
      logger.error("sql exception: ", e);
      return covert(GlobalExceptionUtil.COMMON_DATABASE_EXCEPTION, e);
      // 调取远程接口异常
    } catch (RestClientException e) {
      logger.error("rest client exception: ", e);
      return covert(GlobalExceptionUtil.COMMON_INTERFACE_EXCEPTION, e);
      // 业务逻辑错误
    } catch (Exception e) {
      logger.error("other exception: ", e);
      return covert(GlobalExceptionUtil.DEFAULT_SERVER_ERROR, e);
    }
  }
}
